package com.github.axet.audiorecorder.simple.app

import android.content.Context
import android.net.Uri
import android.os.Environment
import android.util.Log
import java.io.File
import java.text.ParseException
import java.text.SimpleDateFormat
import java.util.*

class SimpleStorage(private val context: Context) {
    
    companion object {
        private const val TAG = "SimpleStorage"
        private const val FOLDER_NAME = "SimpleAudioRecorder"
    }
    
    /**
     * 获取根存储路径
     */
    fun getStoragePath(): File {
        val config = RecordingConfig.fromPreferences(context)
        
        config.storagePath?.let {
            return File(it)
        }
        
        // 默认使用外部存储的音乐目录
        val musicDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_MUSIC)
        val recordingDir = File(musicDir, FOLDER_NAME)
        
        if (!recordingDir.exists()) {
            recordingDir.mkdirs()
        }
        
        return recordingDir
    }
    
    /**
     * 获取今天的录音文件夹
     */
    fun getTodayRecordingFolder(): File {
        val rootDir = getStoragePath()
        
        // 生成今天的日期文件夹名：yyyy-MM-dd
        val dateFormat = SimpleDateFormat("yyyy-MM-dd", Locale.getDefault())
        val todayFolder = dateFormat.format(Date())
        
        val todayDir = File(rootDir, todayFolder)
        if (!todayDir.exists()) {
            val created = todayDir.mkdirs()
            if (!created) {
                Log.w(TAG, "Failed to create today's recording folder: ${todayDir.absolutePath}")
                // 如果创建失败，返回根目录
                return rootDir
            }
        }
        
        return todayDir
    }
    
    /**
     * 生成新的录音文件
     */
    fun getNewRecordingFile(format: String): File {
        val todayDir = getTodayRecordingFolder()
        
        // 生成文件名：Recording_yyyyMMdd_HHmmss.format（保留完整的日期时间信息）
        val timestampFormat = SimpleDateFormat("yyyyMMdd_HHmmss", Locale.getDefault())
        val timestamp = timestampFormat.format(Date())
        val filename = "Recording_${timestamp}.${format}"
        
        return File(todayDir, filename)
    }
    
    /**
     * 生成新的录音文件（带清理功能，用于向后兼容）
     * @deprecated 建议在录音开始前单独调用 cleanupOldRecordings()
     */
    @Deprecated("建议在录音开始前单独调用 cleanupOldRecordings()")
    fun getNewRecordingFileWithCleanup(format: String): File {
        // 每次录音开始时清理旧文件
        cleanupOldRecordings()
        return getNewRecordingFile(format)
    }
    
    /**
     * 清理超过指定天数的录音文件
     */
    fun cleanupOldRecordings() {
        try {
            val rootDir = getStoragePath()
            if (!rootDir.exists()) {
                Log.d(TAG, "Root directory does not exist: ${rootDir.absolutePath}")
                return
            }
            
            // 从配置中获取保留天数
            val config = RecordingConfig.fromPreferences(context)
            val retentionDays = config.retentionDays
            
            // 计算截止日期
            val calendar = Calendar.getInstance()
            calendar.add(Calendar.DAY_OF_YEAR, -retentionDays)
            val cutoffDate = calendar.time
            
            val dateFormat = SimpleDateFormat("yyyy-MM-dd", Locale.getDefault())
            
            Log.d(TAG, "Starting cleanup - retention days: $retentionDays")
            
            val subDirs = rootDir.listFiles() ?: return
            
            for (dir in subDirs) {
                if (dir.isDirectory && isValidDateFolder(dir.name)) {
                    try {
                        val folderDate = dateFormat.parse(dir.name)
                        if (folderDate != null && folderDate.before(cutoffDate)) {
                            Log.d(TAG, "Deleting old folder: ${dir.name}")
                            dir.deleteRecursively()
                        }
                    } catch (e: ParseException) {
                        Log.w(TAG, "Invalid date folder name: ${dir.name}")
                    }
                } else if (dir.isFile && isOldRecordingFile(dir)) {
                    // 处理根目录下的旧文件（兼容旧版本）
                    val fileAge = System.currentTimeMillis() - dir.lastModified()
                    val maxAge = retentionDays * 24 * 60 * 60 * 1000L
                    
                    if (fileAge > maxAge) {
                        Log.d(TAG, "Deleting old file: ${dir.name}")
                        dir.delete()
                    }
                }
            }
            
            Log.d(TAG, "Cleanup completed (retention: $retentionDays days)")
            
        } catch (e: Exception) {
            Log.e(TAG, "Error during cleanup", e)
        }
    }
    
    /**
     * 检查文件夹名是否符合日期格式 yyyy-MM-dd
     */
    private fun isValidDateFolder(folderName: String?): Boolean {
        if (folderName == null || folderName.length != 10) {
            return false
        }
        
        // 简单的格式检查：yyyy-MM-dd
        return folderName.matches(Regex("\\d{4}-\\d{2}-\\d{2}"))
    }
    
    /**
     * 检查是否是旧版本的录音文件
     */
    private fun isOldRecordingFile(file: File): Boolean {
        if (!file.isFile) {
            return false
        }
        
        val name = file.name.lowercase()
        return name.startsWith("recording_") && (name.endsWith(".wav") || name.endsWith(".m4a"))
    }
    

    
    /**
     * 获取存储URI（指向根目录）
     */
    fun getStorageUri(): Uri {
        return Uri.fromFile(getStoragePath())
    }
    
    /**
     * 获取今天录音文件夹的URI
     */
    fun getTodayStorageUri(): Uri {
        return Uri.fromFile(getTodayRecordingFolder())
    }
    
    /**
     * 获取录音统计信息
     */
    fun getRecordingStats(): RecordingStats {
        val rootDir = getStoragePath()
        if (!rootDir.exists()) {
            return RecordingStats(0, 0, 0)
        }
        
        var totalFolders = 0
        var totalFiles = 0
        var totalSize = 0L
        
        val subDirs = rootDir.listFiles()
        if (subDirs != null) {
            for (dir in subDirs) {
                if (dir.isDirectory && isValidDateFolder(dir.name)) {
                    totalFolders++
                    
                    val files = dir.listFiles()
                    if (files != null) {
                        for (file in files) {
                            if (file.isFile && isOldRecordingFile(file)) {
                                totalFiles++
                                totalSize += file.length()
                            }
                        }
                    }
                } else if (dir.isFile && isOldRecordingFile(dir)) {
                    // 兼容根目录下的旧文件
                    totalFiles++
                    totalSize += dir.length()
                }
            }
        }
        
        return RecordingStats(totalFolders, totalFiles, totalSize)
    }
    
    /**
     * 录音统计信息类
     */
    data class RecordingStats(
        val folderCount: Int,
        val fileCount: Int,
        val totalSize: Long
    ) {
        fun getFormattedSize(): String {
            return when {
                totalSize < 1024 -> "$totalSize B"
                totalSize < 1024 * 1024 -> String.format(Locale.getDefault(), "%.1f KB", totalSize / 1024.0)
                else -> String.format(Locale.getDefault(), "%.1f MB", totalSize / (1024.0 * 1024.0))
            }
        }
    }
}